//设备uniqure_code   站点MONITOROWNNETID
var MONITOROWNNETID=GetQueryString("MONITOROWNNETID");
var uniqure_code=GetQueryString("uniqure_code");
var urlStartTime = GetQueryString("startTime");
var urlEndTime =  GetQueryString("endTime");
var initialization =true;

let DataList1=[];
let DataList2=[];
let DataList3=[];
let DataList4=[];
let checkType=false;
(function () {
    initChartTime()

//选择日期触发事件
$('#chart1TimeControl #chart1_time').daterangepicker(null, function (start, end, label) {
    times = $("#chart1TimeControl #chart1_time").val();
    getWaterLevel(undefined,times);
});
$('#chart3TimeControl #chart3_time').daterangepicker(null, function (start, end, label) {
    times = $("#chart3TimeControl #chart3_time").val();
});
$('#lastTimeControl #lastTime').daterangepicker(null, function (start, end, label) {
    times = $("#lastTimeControl #lastTime").val();
    getTableData()
});

$(".cycle a").on("click",function(){
    $(this).addClass("active").siblings().removeClass("active");
})


    if(MONITOROWNNETID !=null ){
        let url = "http://119.97.193.69:97/Jcwlw/Other/getDeviceListByNetId?MONITOROWNNETID="+MONITOROWNNETID;
        $.get(url, function (res) {
            let resData = JSON.parse(res);
            if(resData.data.length>0){
                resData.data.forEach((li)=>{
                    if(li.TYPE == 214){
                        li.list.forEach((item)=>{
                            //JCAA03A010   JCAA03A018中文
                            $("#Chart1Select").append("<option value='"+item.JCAA03A010+"'>"+item.JCAA03A010+"</option>");
                            $("#Chart2Select").append("<option value='"+item.JCAA03A010+"'>"+item.JCAA03A010+"</option>");
                            $("#Chart3Select").append("<option value='"+item.JCAA03A010+"'>"+item.JCAA03A010+"</option>");
                            $("#tableSelect").append("<option value='"+item.JCAA03A010+"'>"+item.JCAA03A010+"</option>");
                           
                        })
                    }
                })
            }
            getAllData();
        })

    }else if(uniqure_code !=null){
        $("#Chart1Select").append("<option value='"+uniqure_code+"'>"+uniqure_code+"</option>");
        $("#Chart2Select").append("<option value='"+uniqure_code+"'>"+uniqure_code+"</option>");
        $("#Chart3Select").append("<option value='"+uniqure_code+"'>"+uniqure_code+"</option>");
        $("#tableSelect").append("<option value='"+uniqure_code+"'>"+uniqure_code+"</option>");
    
        getAllData();
    }

})();
//获取浏览器的参数
function GetQueryString(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
//日期格式化
function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}
//日期选择函数
function GetAnalysisWindowFiterTimes(valuetoid, type, event) {
    var ntime = new Date();
    if (type == 'd') {
            var dstart = ntime.format("MM/dd/yyyy");
            var dend = ntime.format("MM/dd/yyyy");
            $(".timeControl #" + valuetoid).val(dstart + " - " + dend);
    } else if (type == 'w') {
            var wstart = new Date(ntime.getTime() + (24 * 60 * 60 * -6 * 1000)).format("MM/dd/yyyy");
            var wend = ntime.format("MM/dd/yyyy");
            $(".timeControl #" + valuetoid).val(wstart + ' - ' + wend);
    } else if (type == 'm') {
            var mstart = new Date(ntime.getTime() + (24 * 60 * 60 * -30 * 1000)).format("MM/dd/yyyy");
            var mend = ntime.format("MM/dd/yyyy");
            $(".timeControl #" + valuetoid).val(mstart + ' - ' + mend);
    }
    eval(event);
}
//初始化获取图表数据
function getAllData(){
    getWaterLevel()
    getTableData()
    initialization=false;
}
function initChartTime(){
    GetAnalysisWindowFiterTimes('chart1_time', 'd', false); 
   
    let startdate = dateFormat("YYYY-mm-dd", new Date(new Date() -24 * 3600 * 1000 * 7))
    let nowdate = dateFormat("YYYY-mm-dd", new Date(new Date() -24 * 3600 * 1000 * 1))
    layui.use(['laydate'], function(){
        var $=layui.$;
        var laydate = layui.laydate;
        laydate.render({
            elem: '#chart2_time1',
            type: 'date',
            format: 'yyyy-MM-dd',
            value:startdate,
            done: function(value, date, endDate){
               getChart2Data()
            }
        });
        laydate.render({
            elem: '#chart2_time2',
            type: 'date',
            format: 'yyyy-MM-dd',
            value:nowdate,
            done: function(value, date, endDate){
                getChart2Data()
            }
        });
        laydate.render({
            elem: '#chart3_time1',
            type: 'date',
            format: 'yyyy-MM-dd',
            value:startdate,
            done: function(value, date, endDate){
                checkType=true;
                getChart3Data()
            }
        });
        laydate.render({
            elem: '#chart3_time2',
            type: 'date',
            format: 'yyyy-MM-dd',
            value:nowdate,
            done: function(value, date, endDate){
                checkType=true;
                getChart3Data()
            }
        });
    });
    getChart2Data();
    getChart3Data();


    GetAnalysisWindowFiterTimes('chart3_time', 'd', false); 
    GetAnalysisWindowFiterTimes('lastTime', 'd', false); 
}

//获取水位数据
function getWaterLevel(SelectSensorVal,time){
    let selectSense=SelectSensorVal;let times=time;
    if(selectSense == undefined){
        selectSense=$("#Chart1Select option:selected").val(); 
    }
    if(times == undefined){
        times=$("#chart1TimeControl #chart1_time").val();
    }
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
    endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:00:00";
    if(initialization && urlStartTime && urlEndTime){
        startTime = urlStartTime;
        endTime = urlEndTime;
    }
    let url ="http://192.168.9.59:801/apis/result/query214a/?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code="+selectSense;
    $.get(url, function (res) {
        if(res.msg=="success"){
            let data = res.data;
            let column = res.column;
            let dataList=[];
            for(let a=0;a<data.length;a++){
                  let li={}
                  for(let b=0;b<column.length;b++){
                        let key =column[b];
                        li[column[b]]=data[a][b];
                  }
                  dataList.push(li)
            }
            showChart1(dataList)
        }
    })
}
function showChart1(data){
    //JCSJ214A030	Temp（摄氏度）
    //JCSJ214A031	value（米）
    //JCSJ214A040	设备入库时间
    //JCSJ214A050	设备唯一编码
    //JCSJ214A060	设备类型编号（如:101）
    // JCSJ214A070	传感器
    let Xdata=[];let Ydata=[];let TimeData=[]
    data.forEach((item)=>{
        Xdata.push(item.JCSJ214A030*1);
        Ydata.push(item.JCSJ214A031*1)
        TimeData.push(item.time)
  })
  let option={
    chart: {
            type: 'line',
            style: {fontFamily: "'Unica One', sans-serif"},
            plotBorderColor: '#606063',
            zoomType: 'x',
            spacingRight: 20,
            height: 390
    },
    colors: ['#E5561F', '#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
    title: {text: ''},
    credits: {enabled: false},
    exporting: {enabled: false},
    subtitle: {text: ''},
    xAxis: {
        // type: 'datetime',
        categories: TimeData,
        tickInterval:50,
		labels: {
            enabled: true,
			formatter: function() {
				let arr = this.value.split(" ");
				if(arr[1]){
					return arr[1];
				}else{
					return this.value;
				}
				
            }
          }
    },
    yAxis: [{ // Primary yAxis
        title: {
            text: '摄氏度(℃)',
            style: {
                color: '#89A54E'
            }
        },
    }, { // Secondary yAxis
        title: {
            text: '深度(m)',
            style: {
                color: '#4572A7'
            }
        },
        opposite: true
    }],
    tooltip: {
        formatter: function () {
            if(this.series.name == "摄氏度"){
                let row;
                data.forEach((li)=>{
                        if(li.time == this.x){
                            row = li;
                        }
                })
                return "设备编码:[<b>" + row.JCSJ214A050 + "</b>]<br>时间:[" + row.time + "]<br>摄氏度:[" + row.JCSJ214A030 + "]";
            }else{
                let row;
                data.forEach((li)=>{
                    if(li.time == this.x){
                            row = li;
                    }
                })
                return "设备编码:[<b>" + row.JCSJ214A050 + "</b>]<br>时间:[" + row.time + "]<br>深度:[" + row.JCSJ214A031 + "m]";
            }
        }
    },
    plotOptions: {
            spline: {
                lineWidth: 1.5,
                states: {hover: {lineWidth: 2.5}},
                marker: {enabled: false}
            }
    },
    series: [
            {
                type: 'line',
                name: '摄氏度',
                data:Xdata,
                yAxis:0
            }, 
            {
                type: 'line',
                name: '深度',
                data:Ydata,
                yAxis:1
            },
        ]
    }
    $("#chart1").highcharts(option);
}

//table数据
function getTableData(SelectSensorVal,time){
     let selectSense=SelectSensorVal;let times=time;
     if(selectSense == undefined){
        selectSense=$("#tableSelect option:selected").val(); 
    }
    if(times ==undefined){
          times=$(".timeControl #lastTime").val();
    }
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
    endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:59:59";
    if(initialization && urlStartTime && urlEndTime){
        startTime = urlStartTime;
        endTime = urlEndTime;
    }
    let url ="http://192.168.9.59:801/apis/result/query214a?"+"startTime="+startTime+"&endTime="+endTime+"&uniqure_code="+selectSense;
    $.get(url, function (res) {
        if(res.msg=="success"){
            let data = res.data;
            let column = res.column;
            let dataList=[];
            for(let a=0;a<data.length;a++){
                  let li={}
                  for(let b=0;b<column.length;b++){
                        let key =column[b];
                        li[column[b]]=data[a][b];
                  }
                  dataList.push(li)
            }
            layui.use(['table','layer','form','layedit','laydate'], function(){
                var table = layui.table;
                var layer=layui.layer;
                var layedit = layui.layedit;
                var form=layui.form;
                var $=layui.$;
                var laydate = layui.laydate;
                table.render({
                  elem: '#idTest'
                  ,data: dataList
                  ,contentType: "application/x-www-form-urlencoded"
                  ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                      layout: [ 'prev', 'page', 'next', 'skip','limit', 'count',] //自定义分页布局
                      //,curr: 5 //设定初始在第 5 页
                      ,limit:10 //一页显示多少条
                      ,limits:[5,10,15]//每页条数的选择项
                      ,groups: 2 //只显示 2 个连续页码
                      ,first: "首页" //不显示首页
                      ,last: "尾页" //不显示尾页
                      }
                      ,where:{ispage: true }
                      ,even:true
                      ,page: true  //是否启用分页
                      ,done:function(res, curr, count){ }
                      ,cols: [[
                                      //JCSJ214A030	Temp（摄氏度）
                                      //JCSJ214A031	value（米）
                                      //JCSJ214A040	设备入库时间
                                      //JCSJ214A050	设备唯一编码
                                      //JCSJ214A060	设备类型编号（如:101）
                                      // JCSJ214A070	传感器
                                      ,{field:'time',  title: '时间',width:170}
                                      ,{field:'JCSJ214A030',  title: '摄氏度'}
                                      ,{field:'JCSJ214A031', title: '深度（m）'}
                                      ,{field:'JCSJ214A040', title: '设备入库时间'}
                                      ,{field:'JCSJ214A050', title: '设备唯一编码'}
                                      ,{field:'JCSJ214A060', title: '设备类型编号'}
                                      ,{field:'JCSJ214A070', title: '传感器'} 
      
                      ]]
                  });
          })
        }
    }) 
}

//获取图表2的数据
function getChart2Data(){
    let time1=$("#chart2_time1").val();
    let time2=$("#chart2_time2").val();
    let selectSense=$("#Chart2Select option:selected").val(); 
    DataList1=[];
    DataList2=[];
    if(time1 && time2 && selectSense){
        if(initialization && urlStartTime && urlEndTime){
            time1 = urlStartTime;
            time2 = urlEndTime;
        }
        let url ="http://192.168.9.59:801/apis/result/query214a/?"+"startTime="+time1+" 00:00:00&endTime="+time1+" 23:59:59&uniqure_code="+selectSense;
        $.get(url, function (res) {
            if(res.msg=="success"&&res.data){
                let data = res.data;
                let column = res.column;
                for(let a=0;a<data.length;a++){
                      let li={}
                      for(let b=0;b<column.length;b++){
                            let key =column[b];
                            li[column[b]]=data[a][b];
                      }
                      DataList1.push(li)
                }
            }
            let url2 ="http://192.168.9.59:801/apis/result/query214a/?"+"startTime="+time2+" 00:00:00&endTime="+time2+" 23:59:59&uniqure_code="+selectSense;
            $.get(url2, function (res) {
                if(res.msg=="success"&&res.data){
                    let data = res.data;
                    let column = res.column;
                    for(let a=0;a<data.length;a++){
                          let li={}
                          for(let b=0;b<column.length;b++){
                                let key =column[b];
                                li[column[b]]=data[a][b];
                          }
                          DataList2.push(li)
                    }
                }
                showChart2(time1,time2)
            })
        })

        
    }else{
        setTimeout(()=>{
            getChart2Data()
        },1000)
    }
}
//展示图表2
function showChart2(val1,val2){
    let time1=val1;
    let time2=val2;
    //JCSJ214A030	Temp（摄氏度）
    //JCSJ214A031	value（米）
    //JCSJ214A040	设备入库时间
    //JCSJ214A050	设备唯一编码
    //JCSJ214A060	设备类型编号（如:101）
    // JCSJ214A070	传感器
    let Xdata=[];let Ydata=[];
    DataList1.forEach((item)=>{
        Xdata.push({y:item.JCSJ214A031*1,x:new Date(item.time)});
    })
    DataList2.forEach((item)=>{
        Ydata.push({y:item.JCSJ214A031*1,x:new Date(item.time)});
    })
  let option={
    chart: {
            type: 'line',
            style: {fontFamily: "'Unica One', sans-serif"},
            plotBorderColor: '#606063',
            zoomType: 'x',
            spacingRight: 20,
            height: 390
    },
    colors: ['#E5561F', '#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
    title: {text: ''},
    credits: {enabled: false},
    exporting: {enabled: false},
    subtitle: {text: ''},
    xAxis: {
        type: 'datetime',
        // categories: TimeData,
        // crosshair: true,
    },
    yAxis: [
        { // Secondary yAxis
        title: {
            text: '深度(m)',
            style: {
                color: '#4572A7'
            }
        },
        }
    ],
    tooltip: {
        formatter: function () {
            let time=dateFormat("YYYY-mm-dd HH:MM:SS", this.x)
                return "时间:[" + time + "]<br>深度:[" + this.y + "m]";
        }
    },
    plotOptions: {
            spline: {
                lineWidth: 1.5,
                states: {hover: {lineWidth: 2.5}},
                marker: {enabled: false}
            }
    },
    series: [
            {
                type: 'line',
                name: time1,
                data:Xdata,
                // yAxis:0
            }, 
            {
                type: 'line',
                name:time2,
                data:Ydata,
                // yAxis:1
            },
        ]
    }
    $("#chart2").highcharts(option);
}
//获取图表3的数据
function getChart3Data(){
    let time1=$("#chart3_time1").val();
    let time2=$("#chart3_time2").val();
    let selectSense=$("#Chart3Select option:selected").val(); 
    DataList3=[];
    DataList4=[];
    if(time1 && time2 && selectSense){
        let url1;
        let url2;
        if(!checkType){
            url1 ="http://192.168.9.59:801/apis/result/query214a/?"+"startTime="+time1+" 00:00:00&endTime="+time1+" 23:59:59&uniqure_code="+selectSense;
            url2 ="http://192.168.9.59:801/apis/result/query214a/?"+"startTime="+time2+" 00:00:00&endTime="+time2+" 23:59:59&uniqure_code="+selectSense;
        }else{
            let text =$(".chartTime3 .active")[0].innerText;
            if(text == "今天"){
                time3= dateFormat("YYYY-mm-dd", new Date(new Date(time1) -24 * 3600 * 1000))
                time4= dateFormat("YYYY-mm-dd", new Date(new Date(time2) -24 * 3600 * 1000))
            }else if(text == "一周"){
                time3= dateFormat("YYYY-mm-dd", new Date(new Date(time1) -7*24 * 3600 * 1000))
                time4= dateFormat("YYYY-mm-dd", new Date(new Date(time2) -7*24 * 3600 * 1000))
            }else if(text == "一月"){
                time3= dateFormat("YYYY-mm-dd", new Date(new Date(time1) -30*24 * 3600 * 1000))
                time4= dateFormat("YYYY-mm-dd", new Date(new Date(time2) -30*24 * 3600 * 1000))
            }
            url1 ="http://192.168.9.59:801/apis/result/query214a/?"+"startTime="+time3+" 00:00:00&endTime="+time1+" 23:59:59&uniqure_code="+selectSense;
            url2 ="http://192.168.9.59:801/apis/result/query214a/?"+"startTime="+time4+" 00:00:00&endTime="+time2+" 23:59:59&uniqure_code="+selectSense;
        }
        $.get(url1, function (res) {
            if(res.msg=="success"&&res.data){
                let data = res.data;
                let column = res.column;
                for(let a=0;a<data.length;a++){
                      let li={}
                      for(let b=0;b<column.length;b++){
                            let key =column[b];
                            li[column[b]]=data[a][b];
                      }
                      DataList3.push(li)
                }
            }
            $.get(url2, function (res) {
                if(res.msg=="success"&&res.data){
                    let data = res.data;
                    let column = res.column;
                    for(let a=0;a<data.length;a++){
                          let li={}
                          for(let b=0;b<column.length;b++){
                                let key =column[b];
                                li[column[b]]=data[a][b];
                          }
                          DataList4.push(li)
                    }
                }
                showChart3(time1,time2)
            })
        })
    }else{
        setTimeout(()=>{
            getChart3Data()
        },1000)
    }
}
//展示图表3
function showChart3(val1,val2){
    let time1=val1;
    let time2=val2;
    //JCSJ214A030	Temp（摄氏度）
    //JCSJ214A031	value（米）
    //JCSJ214A040	设备入库时间
    //JCSJ214A050	设备唯一编码
    //JCSJ214A060	设备类型编号（如:101）
    // JCSJ214A070	传感器
    let Xdata=[];let Ydata=[];
    DataList3.forEach((item)=>{
        Xdata.push({y:item.JCSJ214A031*1,x:new Date(item.time)});
    })
    DataList4.forEach((item)=>{
        Ydata.push({y:item.JCSJ214A031*1,x:new Date(item.time)});
    })
  let option={
    chart: {
            type: 'line',
            style: {fontFamily: "'Unica One', sans-serif"},
            plotBorderColor: '#606063',
            zoomType: 'x',
            spacingRight: 20,
            height: 390
    },
    colors: ['#E5561F', '#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
    title: {text: ''},
    credits: {enabled: false},
    exporting: {enabled: false},
    subtitle: {text: ''},
    xAxis: {
        type: 'datetime',
        // categories: TimeData,
        // crosshair: true,
    },
    yAxis: [
        { // Secondary yAxis
        title: {
            text: '深度(m)',
            style: {
                color: '#4572A7'
            }
        },
        }
    ],
    tooltip: {
        formatter: function () {
            let time=dateFormat("YYYY-mm-dd HH:MM:SS", this.x)
                return "时间:[" + time + "]<br>深度:[" + this.y + "m]";
        }
    },
    plotOptions: {
            spline: {
                lineWidth: 1.5,
                states: {hover: {lineWidth: 2.5}},
                marker: {enabled: false}
            }
    },
    series: [
            {
                type: 'line',
                name: time1,
                data:Xdata,
                // yAxis:0
            }, 
            {
                type: 'line',
                name:time2,
                data:Ydata,
                // yAxis:1
            },
        ]
    }
    $("#chart3").highcharts(option);
}

//图表3日期
function GetChart3Times(time1,time2,type){
    // 'chart3_time1','chart3_time2','d', false
    checkType=false;
    var ntime = new Date();
    var tiemStart;
    var tiemEnd;
    if (type == 'd') {
        tiemStart = ntime.format("yyyy-MM-dd");
        tiemEnd = ntime.format("yyyy-MM-dd");
    } else if (type == 'w') {
        tiemStart = new Date(ntime.getTime() + (24 * 60 * 60 * -6 * 1000)).format("yyyy-MM-dd");
        tiemEnd = ntime.format("yyyy-MM-dd");
    } else if (type == 'm') {
        tiemStart = new Date(ntime.getTime() + (24 * 60 * 60 * -30 * 1000)).format("yyyy-MM-dd");
        tiemEnd= ntime.format("yyyy-MM-dd");
    }
    $("#chart3_time1")[0].value=tiemStart;
    $("#chart3_time2")[0].value=tiemEnd;
    eval(event);
}